import Cookies from 'js-cookie'
import { defineStore } from 'pinia'
import { ref } from 'vue'

import { accountErrorMap, ResultEnum } from '@/apis/http/httpEnum'
import type { UserInfoModel } from '@/apis/model/auth'
import { jumpNameAfterLogin, jumpNameAfterSignOut, storesKey } from '@/config'
import router from '@/router'

export const useAppStore = defineStore(
  storesKey.app,
  () => {
    const token = ref<string | undefined>()
    const isLogined = computed(() => !!token.value)
    const userInfo = ref<UserInfoModel>()
    const logo = ref('')

    const loginErrorResult = ref<{
      code: number
      message: string
      type: 'account' | 'password'
    }>()

    const userInfoAction = async () => {
      const res = await getUserApi()
      userInfo.value = res ?? {}
    }

    /**
     * 登录
     * @param data 登录参数
     * @returns Promise<boolean>
     */
    const signInAction = async (data: Record<string, string>) => {
      const res = await signInApi(data)
      if (res.code === ResultEnum.SUCCESS) {
        const data = res.data
        loginErrorResult.value = undefined
        userInfo.value = data.user_info
        token.value = data.token
        Cookies.set('token', token.value!, { sameSite: 'lax' })

        const redirect = router.currentRoute.value.query.redirect as string
        router.replace(redirect || { name: jumpNameAfterLogin })
      } else {
        if (
          [ResultEnum.WRONG_PASSWORD, ResultEnum.WRONG_PASSWORD].includes(
            res.code
          )
        ) {
          loginErrorResult.value = {
            code: res.code,
            message: '账号或者密码错误，请重试',
            type: 'password'
          }
        } else {
          const type = accountErrorMap.includes(res.code)
            ? 'account'
            : 'password'

          loginErrorResult.value = {
            type,
            code: res.code,
            message: res.message
          }
        }
        throw new Error('login error')
      }
    }

    const clearLoginInfo = () => {
      userInfo.value = undefined
      token.value = undefined
    }
    /**
     * 登出
     * @returns void
     */
    const signOutAction = async () => {
      try {
        return await signOutApi()
      } finally {
        clearLoginInfo()
        resetFilterState()
        const fullPath = router.currentRoute.value.fullPath
        const redirect = router.currentRoute.value.query.redirect as string
        router.replace({
          name: jumpNameAfterSignOut,
          query: { redirect: redirect || fullPath }
        })
      }
    }

    /**
     * 不调用接口，仅退出
     */
    const signOut = () => {
      clearLoginInfo()
      resetFilterState()
      const fullPath = router.currentRoute.value.fullPath
      const redirect = router.currentRoute.value.query.redirect as string
      router.replace({
        name: jumpNameAfterSignOut,
        query: { redirect: redirect || fullPath }
      })
    }

    const signOutNoJump = () => {
      signOutApi().finally(() => {
        clearLoginInfo()
      })
    }
    const certFilterState = ref({
      provider: '',
      status: '',
      domain_keyword: ''
    })
    function setCertFilterState(data: typeof certFilterState.value) {
      Object.assign(certFilterState.value, data)
    }
    function resetFilterState() {
      certFilterState.value = {
        provider: '',
        status: '',
        domain_keyword: ''
      }
    }
    return {
      loginErrorResult,
      logo,
      token,
      userInfo,
      isLogined,
      signOut,
      userInfoAction,
      signInAction,
      signOutAction,
      clearLoginInfo,
      signOutNoJump,
      certFilterState,
      setCertFilterState,
      resetFilterState
    }
  },
  { persist: true }
)
